from BlogElements import BlogPosting;
from BlogElements import BlogComment;
from BlogElements import BlogProfile;

from xml.sax import ContentHandler;
import feedparser;
import xml.sax;
import time;
import sys;
import re;

updateUrl = 'http://spaces.live.com/changes.aspx?mkt=en-us';

class LiveSpaceFeedExtractor:
    def extract(self, url):
        return url + 'feed.rss';

class LiveSpaceFeedPageParser:     
    def parse(self, page):
        blogs = [];
        profile = BlogProfile();
        try:
            doc = feedparser.parse(page);
        except Exception:
            return 0, blogs;
        
        i = 0;
        if len(doc.feed.keys()) <> 0:
           profile.title = doc.feed['title'];
           for entry in doc.entries:
               blog = BlogPosting();
               blog.title = entry['title'];
               blog.date = time.mktime(entry['updated_parsed']);
               blog.description = entry['summary'];
               blog.url = entry['link'];
               if entry.has_key('wfw_commentrss'):
                   blog.commentUrl = entry['wfw_commentrss'];
               blogs.append(blog);
               i += 1;
        return profile, blogs;


class LiveSpaceCommentPageParser:
    def __init__(self):
        self.spacePattern = re.compile('http://[^.]*?.spaces.live.com');
    
    def parse(self, page):
        comments = [];
        doc = feedparser.parse(page);
        if doc:
            for entry in doc.entries:
                comment = BlogComment();
                comment.content = entry['live_commentbody'];
                comment.authorName = entry['live_authorname'];
                if entry.has_key('live_authoremail'):
                    comment.authorEmail = entry['live_authoremail'];
                comment.authorId = entry['live_authorcid'];
                detail = entry['summary_detail']['value'];
                result = self.spacePattern.search(detail);
                if result:
                    comment.authorUrl += result.group();
                comments.append(comment);
        return comments;
                


class LiveSpaceUpdateParser(ContentHandler):
    def __init__(self):
        self.clear();
        
    def parse(self, page):
        xml.sax.parse(page, self);
        return self.urls;
    
    def clear(self):
        self.urls = [];
        
    def startDocument(self):
        self.clear();
        
    def startElement(self, name, attrs):
        if name == 'weblog':
            url = str(attrs['url']);
            self.urls.append(url);
        elif name == 'weblogUpdates':
            updateTime = str(attrs['updated']);
            print 'updating at', time.asctime(),':',updateTime;
        
class LiveSpaceUserNameExtractor:
    def __init__(self):
        self.pattern = re.compile('http://([^/.]+).spaces');
        
    def extract(self, homeUrl):
        result = re.match(self.pattern, homeUrl);
        if result:
            groups = result.groups();
            if(len(groups) > 1):
                return groups[0];
        return '';
                
        
class LiveSpaceProfileUrlExtractor:
    def __init__(self):
        self.userNameExtractor = LiveSpaceUserNameExtractor();
        
    def extract(self, homeUrl):
        username = self.userNameExtractor.extract(homeUrl);
        if username == '':
            return '';
        url = 'http://' + username + '.spaces.live.com/profile/feed.rss';
        return url;
        
class LiveSpaceProfileParser:
    def parse(self, filePath):
        doc = feedparser.parse(filePath);
        profile = BlogProfile();
        profile.title = doc.feed.title;
        profile.author = doc.feed.live_alias;
        profile.userid = doc.feed.live_id;
        for entry in doc.entries:
            if entry.has_key('live_interests'):
                profile.interests = entry['live_interests'];
            if entry.has_key('live_age'):
                profile.age = int(entry['live_age']);
            if entry.has_key('live_gender'):
                profile.gender = entry['live_gender'];
            if entry.has_key('live_occupation'):
                profile.occupation = entry['live_occupation'];
            if entry.has_key('live_homecountryorregion'):
                profile.homeCountry = entry['live_homecountryorregion'];
            if entry.has_key('live_homecity'):
                profile.homeCity = entry['live_homecity'];
            if entry.has_key('live_reallastname') or entry.has_key('live_realfirstname'):
                profile.realName = '';
                if entry.has_key('live_realfirstname'):
                    profile.realName += entry['live_realfirstname'] + ' ';
                if entry.has_key('live_reallastname'):
                    profile.realName += entry['live_reallastname'];  
            if entry.has_key('live_placeslived'):
                profile.placesLived = entry['live_placeslived'];
            if entry.has_key('live_maritalstatus'):
                profile.maritalStatus = entry['live_maritalstatus'];
        return profile;
                
    

if __name__ == '__main__':
    import sys;
    if sys.argv[1]== '--feed':
        parser = LiveSpaceFeedPageParser();
        blogs = parser.parse(sys.argv[2]);
        for blog in parser.blogs:
            print blog;
    elif sys.argv[1] == '--profile':
        parser = LiveSpaceProfileParser();
        profile = parser.parse(sys.argv[2]);
        print profile;
        